package com.vmc.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.vmc.exception.VMCException;

public class SingleInstanceUtility {
	
	static Logger logger = LogManager.getLogger(SingleInstanceUtility.class);
	
	private static final String FILE_NAME = "./%s.ins";
	private static final String OTHER_INSTANCE_ERROR = "App is already running in a different instance.";
	
	private static SingleInstanceUtility instance;
	
	private SingleInstanceUtility() {
		
	}
	
	public static SingleInstanceUtility getInstance() {
		if (instance == null) {
			instance = new SingleInstanceUtility();
		}
		return instance;
	}
	
	public boolean isInstanceExisting(String code) {
		File file = new File(String.format(FILE_NAME, code));
		return file.exists();
	}
	
	public void ensureSingleInstance(String code) throws VMCException {
		logger.info("Ensuring single instance of the application...");
		if (!this.isInstanceExisting(code)) {
			try {
				FileWriter fw = new FileWriter(new File(String.format(FILE_NAME, code)));
				BufferedWriter bw = new BufferedWriter(fw);
				bw.write("instance");
				bw.close();
				fw.close();
			}
			catch (IOException e) {
				logger.error("An error occured while reading the file.", e);
				throw new VMCException(e.getMessage());
			}
		}
		else {
			logger.error("Another instance already exists");
			throw new VMCException(OTHER_INSTANCE_ERROR);
		}
	}
	
	public void endSingleInstance(String code) throws VMCException {
		logger.info("Removing single instance marker.");
		if (this.isInstanceExisting(code)) {
			File file = new File(String.format(FILE_NAME, code));
			file.delete();
			logger.info("Done.");
		}
	}
}
